package com.jinpeng.common.aspect;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.jdbc.DataSourceBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.PlatformTransactionManager;

import javax.sql.DataSource;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

@Configuration
@MapperScan(basePackages = "com.jinpeng.*.dao")
public class DataSourceConfig {

    //private Logger logger = LoggerFactory.getLogger(this.getClass());

    //配置第一个数据源
    @Primary
    @Bean(name = "primaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.primary")
    public DataSource primaryDataSource() {
        //修改成jdbc-url
        //DataSource dataSource = DataSourceBuilder.create().build();
        DataSource dataSource = new com.alibaba.druid.pool.DruidDataSource();
        return dataSource;
    }

    //配置第二个数据源
    //@Primary
    @Bean(name = "secondaryDataSource")
    @ConfigurationProperties(prefix = "spring.datasource.second")
    public DataSource secondaryDataSource() {
        DataSource dataSource = DataSourceBuilder.create().build();
        //修改成url
        //DataSource dataSource = new com.alibaba.druid.pool.DruidDataSource();
        return dataSource;
    }


    @Bean("dynamicDataSource")
    public DataSource dynamicDataSource() throws Exception {
        DynamicDataSource dataSource = new DynamicDataSource();
        //设置默认数据源，当无法映射到数据源时会使用默认数据源
        dataSource.setDefaultTargetDataSource(primaryDataSource());
        Map<Object, Object> targetDataSources = new HashMap<>(2);
        targetDataSources.put("primaryDataSource", primaryDataSource());
        targetDataSources.put("secondaryDataSource", secondaryDataSource());
        DynamicDatasourceHolder.dataSourceKeys.addAll(targetDataSources.keySet());
        //设置数据源映射
        dataSource.setTargetDataSources(targetDataSources);
        dataSource.afterPropertiesSet();
        return dataSource;
    }

    /**
     * 配置 SqlSessionFactoryBean
     *
     * @return the sql session factory bean
     * @throws Exception
     * @ConfigurationProperties 在这里是为了将 MyBatis 的 mapper 位置和持久层接口的别名设置到Bean的属性中，
     * 如果没有使用 *.xml 则可以不用该配置，否则将会产生 invalid bond statement 异常
     */
    @Bean
    public SqlSessionFactory sqlSessionFactoryBean() throws Exception {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        // 配置数据源，此处配置为关键配置，如果没有将 dynamicDataSource 作为数据源则不能实现切换
        sqlSessionFactoryBean.setDataSource(dynamicDataSource());
        //此处设置为了解决找不到mapper文件的问题
        org.apache.ibatis.session.Configuration conf = new org.apache.ibatis.session.Configuration();
        conf.setMapUnderscoreToCamelCase(true);
        sqlSessionFactoryBean.setConfiguration(conf);
        sqlSessionFactoryBean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/**/*Mapper.xml"));
        sqlSessionFactoryBean.setTypeAliasesPackage("com.jinpeng.**.domain");
        return sqlSessionFactoryBean.getObject();
    }

    /**
     * 注入DataSourceTransactionManager 用于事务管理
     *
     * @throws Exception
     */
    @Bean
    public PlatformTransactionManager transactionManager() throws Exception {
        return new DataSourceTransactionManager(dynamicDataSource());
    }

}
